package com.zhang.flink.example;

import com.zhang.flink.bean.ItemViewCountPerWindow;
import com.zhang.flink.bean.PageViewCountWindow;
import com.zhang.flink.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.Random;

/**
 * @title: pv统计(解决数据倾斜)
 * @author: zhang
 * @date: 2022/3/31 16:06
 */
public class PageViewCountPlus {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        env
                .readTextFile("/Users/apple/project-git/flink-example/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new UserBehavior(
                                fields[0],
                                fields[1],
                                fields[2],
                                fields[3],
                                Long.parseLong(fields[4]) * 1000L
                        );
                    }
                })
                .filter(data -> "pv".equals(data.type))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .map(data -> Tuple2.of("pv_" + new Random().nextInt(4), data))
                .returns(Types.TUPLE(Types.STRING, Types.POJO(UserBehavior.class)))
                .keyBy(r -> r.f0)
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                .aggregate(new CountAgg(), new WindowResult())
                .keyBy(r -> r.windowEndTime)
                .process(new CountProcess())
                .print();
        env.execute();
    }

    public static class CountAgg implements AggregateFunction<Tuple2<String, UserBehavior>, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(Tuple2<String, UserBehavior> value, Long accumulator) {
            return accumulator + 1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, PageViewCountWindow, String, TimeWindow> {
        @Override
        public void process(String s, ProcessWindowFunction<Long, PageViewCountWindow, String, TimeWindow>.Context context, Iterable<Long> elements, Collector<PageViewCountWindow> out) throws Exception {
            Long cnt = elements.iterator().next();
            out.collect(new PageViewCountWindow(
                    cnt,
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }

    public static class CountProcess extends KeyedProcessFunction<Long, PageViewCountWindow, String> {
        private ValueState<Long> pvCntState;

        @Override
        public void open(Configuration parameters) throws Exception {
            pvCntState = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>(
                            "pv-cnt", Types.LONG
                    )
            );
        }

        @Override
        public void processElement(PageViewCountWindow value, KeyedProcessFunction<Long, PageViewCountWindow, String>.Context ctx, Collector<String> out) throws Exception {
            if (pvCntState.value() == null) {
                pvCntState.update(value.count);
            } else {
                pvCntState.update(pvCntState.value() + value.count);
            }
            ctx.timerService().registerEventTimeTimer(value.windowEndTime);
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Long, PageViewCountWindow, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
            out.collect("" +
                    "窗口：" + new Timestamp(timestamp - 1L) + " " +
                    "pv: " + pvCntState.value());
            pvCntState.clear();
        }
    }


}
